package com.learn.training.multithread.chapter10.demo2;

import java.util.concurrent.RecursiveAction;

public class RecursiveActionExample extends RecursiveAction {
    // 定义任务拆分的阈值，任务小于该值时直接计算。
    private static final int THRESHOLD = 10;
    private final int[] array;
    private final int start;
    private final int end;

    public RecursiveActionExample(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        if (end - start <= THRESHOLD){
            // 直接处理小任务
            for (int i = start; i <= end; i++){
                array[i] *= 2;
            }
        }else {
            // 大任务拆分成两个子任务
            int mid = (start + end)/2;
            RecursiveActionExample leftTask = new RecursiveActionExample(array, start, mid);
            RecursiveActionExample rightTask = new RecursiveActionExample(array, mid, end);
            //并行执行子任务
            invokeAll(leftTask, rightTask);
        }
    }
}
